import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zentoon_flutter/screens/splash_screen.dart';
import '../providers/comic_provider.dart';
import '../widgets/bottom_nav_bar.dart';
import 'discover_screen.dart';
import 'home/home_index.dart';
import 'new_discover_screen.dart';
import 'premium_screen.dart';
import 'bookshelf_screen.dart';
import 'mine/profile_screen.dart';

class MainScreen extends ConsumerStatefulWidget {
  const MainScreen({super.key});

  @override
  ConsumerState<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends ConsumerState<MainScreen> {
  // 用于缓存已加载的页面
  final Map<int, Widget> _cachedScreens = {};

  // 记录哪些页面已经被访问过
  final Set<int> _visitedPages = {0}; // 默认首页已访问

  @override
  void initState() {
    super.initState();
    // 预加载首页
    _cachedScreens[0] = const HomeIndexScrren();
    // _initAppsFlyer();
  }

  Future<void> _initAppsFlyer() async {
    final prefs = await SharedPreferences.getInstance();
    final isFirstLaunch = prefs.getBool('has_launched_before') ?? true;
    if (isFirstLaunch == false) {
      final AppsFlyerOptions appsFlyerOptions = AppsFlyerOptions(
        afDevKey: "pJpKGnELxYueV2QxpgztDh",
        appId: "6738265376",
        showDebug: true,
        timeToWaitForATTUserAuthorization: 15,
        disableAdvertisingIdentifier: false,
        disableCollectASA: false,
        manualStart: false,
      );

      appsflyerSdk = AppsflyerSdk(appsFlyerOptions);

      appsflyerSdk!.onInstallConversionData((data) {
        print("📊 AppsFlyer安装转化数据: $data");
      });

      appsflyerSdk!.onDeepLinking((data) {
        print("🔗 AppsFlyer深度链接: $data");
      });

      appsflyerSdk!.initSdk(
        registerConversionDataCallback: true,
        registerOnAppOpenAttributionCallback: true,
        registerOnDeepLinkingCallback: true,
      );
    }
  }

  Widget _getScreen(int index) {
    // 如果页面已缓存，直接返回
    if (_cachedScreens.containsKey(index)) {
      return _cachedScreens[index]!;
    }

    // 懒加载页面
    Widget screen;
    switch (index) {
      case 0:
        screen = const HomeIndexScrren();
        break;
      case 1:
        screen = const DiscoverPage();
        break;
      case 2:
        screen = const PremiumScreen();
        break;
      case 3:
        screen = const BookshelfScreen();
        break;
      case 4:
        screen = const ProfileScreen();
        break;
      default:
        screen = const SizedBox();
    }

    // 缓存页面
    _cachedScreens[index] = screen;
    _visitedPages.add(index);
    return screen;
  }

  @override
  Widget build(BuildContext context) {
    final currentIndex = ref.watch(bottomNavIndexProvider);

    // 构建页面列表，只包含已访问的页面
    final screens = List.generate(5, (index) {
      if (_visitedPages.contains(index)) {
        return _getScreen(index);
      } else {
        return const SizedBox(); // 占位符
      }
    });

    // 确保当前页面被加载
    if (!_visitedPages.contains(currentIndex)) {
      _getScreen(currentIndex);
      screens[currentIndex] = _cachedScreens[currentIndex]!;
    }

    return Scaffold(
      body: IndexedStack(
        index: currentIndex,
        children: screens,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.black,
        elevation: 0,
        selectedItemColor: const Color(0xffb73981),
        unselectedItemColor: Colors.white70,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        currentIndex: currentIndex,
        onTap: (int index) {
          ref.read(bottomNavIndexProvider.notifier).state = index;
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.explore_outlined),
            activeIcon: Icon(Icons.explore),
            label: 'Discover',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.category_outlined),
            activeIcon: Icon(Icons.category),
            label: 'Genres',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.star_outline),
            activeIcon: Icon(Icons.star),
            label: 'Premium',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.bookmarks_outlined),
            activeIcon: Icon(Icons.bookmarks),
            label: 'Bookshelf',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person_outline),
            activeIcon: Icon(Icons.person),
            label: 'Mine',
          ),
        ],
      ),
    );
  }
}
